package com.spring.web.controller;

import org.springframework.http.HttpStatus;
import org.springframework.util.CollectionUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Objects;

public class BaseController {

	protected static final String APPLICATION_JSON = "application/json";

	protected String getRemoteHost() {
		String url = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest()
				.getHeader("referer");
		URI uri;
		try {
			uri = new URI(url);
		} catch (URISyntaxException e) {
//            log.warn("getRemoteHost url:{}, e:{}", url, e);
			return null;
		}
		return uri.getHost();
	}

	protected HttpStatus foundHttpStatus(Object object) {
		boolean isHasContent;
		if (object instanceof List) {
			isHasContent = !CollectionUtils.isEmpty((List) object);
		} else {
			isHasContent = Objects.nonNull(object);
		}
		return isHasContent ? HttpStatus.OK : HttpStatus.NO_CONTENT;
	}

}